package com.zxs.collect.service.impl;

import client.ProductClient;
import com.zxs.collect.mapper.CollectMapper;
import com.zxs.collect.service.CollectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import parm.ProductIdsParam;
import pojo.Collect;
import utils.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zxs
 * *8 15:51
 */
@Service
@Slf4j
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private ProductClient productClient;

    @Override
    public R save(Collect collect) {
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();

        //先查询收藏表中是否存在,根据用户id和商品id唯一确认
        queryWrapper.eq("user_id", collect.getUserId());
        queryWrapper.eq("product_id", collect.getProductId());

        Long count = collectMapper.selectCount(queryWrapper);

        if (count > 0) {
            //收藏已存在
            return R.fail("收藏已存在,多次添加失败");
        }
        //不存在，则更新对象collect 的收藏时间
        collect.setCollectTime(System.currentTimeMillis());
        int insert = collectMapper.insert(collect);
        log.info("收藏业务结束", insert);
        return R.ok("收藏成功");
    }

    @Override
    public R list(Collect collect) {

        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", collect.getUserId());
        queryWrapper.select("product_id");
        List<Object> list = collectMapper.selectObjs(queryWrapper);

        ProductIdsParam productIdsParam = new ProductIdsParam();

        List<Integer> idList = new ArrayList<Integer>();
        for (Object o : list) {
            idList.add((Integer) o);
        }
        productIdsParam.setProductIds(idList);

        R r = productClient.collectList(productIdsParam);

        return r;
    }

    @Override
    public R remove(Collect collect) {
        Integer userId = collect.getUserId();
        Integer productId = collect.getProductId();
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("product_id", productId);

        int delete = collectMapper.delete(queryWrapper);

        if (delete == 0) {
            return R.fail("收藏删除失败！");
        }
        return R.ok("收藏删除成功");

    }

    /**
     * 后台要删除商品之前，商品id对应的收藏信息
     *
     * @param productId
     * @return
     */
    @Override
    public R adminRemove(Integer productId) {
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("product_id", productId);

        int rows = collectMapper.delete(queryWrapper);

        return R.ok(rows);
    }
}
